#!/usr/bin/env pwsh
# 快速测试脚本 - 模拟各种场景快速验证服务稳定性

param(
    [string]$Url = "http://localhost:8215"
)

$ErrorActionPreference = "Continue"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  快速测试脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

function Test-Query {
    param(
        [string]$query,
        [string]$description,
        [int]$timeout = 10
    )
    
    Write-Host "测试: $description" -ForegroundColor Yellow
    Write-Host "  查询: $query" -ForegroundColor Gray
    
    $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
    
    try {
        $body = @{
            query = $query
            sessionId = "test-$(Get-Random)"
        } | ConvertTo-Json
        
        $response = Invoke-RestMethod -Uri "$Url/api/agent/query" `
            -Method Post `
            -Body $body `
            -ContentType "application/json" `
            -TimeoutSec $timeout
        
        $stopwatch.Stop()
        
        if ($response.success) {
            Write-Host "  ✅ 成功 (${stopwatch.ElapsedMilliseconds}ms)" -ForegroundColor Green
            Write-Host "  回复: $($response.summary.Substring(0, [Math]::Min(50, $response.summary.Length)))..." -ForegroundColor Gray
        } else {
            Write-Host "  ⚠️ 失败 (${stopwatch.ElapsedMilliseconds}ms)" -ForegroundColor Yellow
            Write-Host "  错误: $($response.summary)" -ForegroundColor Yellow
        }
    }
    catch {
        $stopwatch.Stop()
        Write-Host "  ❌ 异常 (${stopwatch.ElapsedMilliseconds}ms)" -ForegroundColor Red
        Write-Host "  错误: $($_.Exception.Message)" -ForegroundColor Red
    }
    
    Write-Host ""
}

# ========== 测试1：健康检查 ==========
Write-Host "【测试1】基础健康检查" -ForegroundColor Cyan
Write-Host ""

try {
    $health = Invoke-RestMethod -Uri "$Url/api/health" -Method Get -TimeoutSec 5
    Write-Host "✅ 服务健康状态: $($health.status)" -ForegroundColor Green
} catch {
    Write-Host "❌ 健康检查失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host ""
    Write-Host "服务未启动或无法访问，请先启动服务！" -ForegroundColor Yellow
    exit 1
}

Write-Host ""

# ========== 测试2：闲聊模式 ==========
Write-Host "【测试2】闲聊模式测试（应该秒回）" -ForegroundColor Cyan
Write-Host ""

Test-Query "你好" "问候语" 5
Test-Query "你是谁" "自我介绍" 5
Test-Query "谢谢" "礼貌用语" 5

# ========== 测试3：拒绝模式 ==========
Write-Host "【测试3】拒绝模式测试（应该秒回）" -ForegroundColor Cyan
Write-Host ""

Test-Query "今天天气怎么样" "天气查询" 5
Test-Query "推荐一本书" "推荐类" 5

# ========== 测试4：简单数据查询 ==========
Write-Host "【测试4】简单数据查询（使用Mock数据）" -ForegroundColor Cyan
Write-Host ""

# 先切换到Mock模式（避免等待AI）
Write-Host "提示：如需快速测试，请在 appsettings.json 中设置：" -ForegroundColor Yellow
Write-Host '  "Qwen": { "UseMock": true }' -ForegroundColor Gray
Write-Host ""

Test-Query "查询设备统计" "设备查询" 30

# ========== 测试5：并发测试 ==========
Write-Host "【测试5】并发测试（3个请求同时发送）" -ForegroundColor Cyan
Write-Host ""

$jobs = @()
$jobs += Start-Job -ScriptBlock {
    param($url)
    Invoke-RestMethod -Uri "$url/api/agent/query" `
        -Method Post `
        -Body '{"query":"你好","sessionId":"concurrent-1"}' `
        -ContentType "application/json" `
        -TimeoutSec 10
} -ArgumentList $Url

$jobs += Start-Job -ScriptBlock {
    param($url)
    Invoke-RestMethod -Uri "$url/api/agent/query" `
        -Method Post `
        -Body '{"query":"你是谁","sessionId":"concurrent-2"}' `
        -ContentType "application/json" `
        -TimeoutSec 10
} -ArgumentList $Url

$jobs += Start-Job -ScriptBlock {
    param($url)
    Invoke-RestMethod -Uri "$url/api/agent/query" `
        -Method Post `
        -Body '{"query":"谢谢","sessionId":"concurrent-3"}' `
        -ContentType "application/json" `
        -TimeoutSec 10
} -ArgumentList $Url

Write-Host "等待并发请求完成..." -ForegroundColor Gray
$results = $jobs | Wait-Job | Receive-Job

$successCount = ($results | Where-Object { $_.success }).Count
Write-Host "并发测试结果: $successCount/3 成功" -ForegroundColor $(if ($successCount -eq 3) { "Green" } else { "Yellow" })

$jobs | Remove-Job

Write-Host ""

# ========== 测试6：连续快速请求 ==========
Write-Host "【测试6】连续快速请求（模拟快速点击）" -ForegroundColor Cyan
Write-Host ""

for ($i = 1; $i -le 5; $i++) {
    Write-Host "  第 $i 次请求..." -NoNewline
    
    try {
        $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
        $body = @{
            query = "你好"
            sessionId = "rapid-$i"
        } | ConvertTo-Json
        
        $response = Invoke-RestMethod -Uri "$Url/api/agent/query" `
            -Method Post `
            -Body $body `
            -ContentType "application/json" `
            -TimeoutSec 5
        
        $stopwatch.Stop()
        Write-Host " ✅ ${stopwatch.ElapsedMilliseconds}ms" -ForegroundColor Green
    }
    catch {
        Write-Host " ❌ 失败" -ForegroundColor Red
    }
    
    Start-Sleep -Milliseconds 100
}

Write-Host ""

# ========== 测试7：超时恢复 ==========
Write-Host "【测试7】超时恢复测试" -ForegroundColor Cyan
Write-Host ""

Write-Host "发送一个可能超时的请求..." -ForegroundColor Gray
try {
    $body = @{
        query = "查询所有数据"
        sessionId = "timeout-test"
    } | ConvertTo-Json
    
    $response = Invoke-RestMethod -Uri "$Url/api/agent/query" `
        -Method Post `
        -Body $body `
        -ContentType "application/json" `
        -TimeoutSec 10
    
    Write-Host "✅ 请求成功" -ForegroundColor Green
}
catch {
    Write-Host "⚠️ 请求超时或失败（预期）" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "等待3秒后发送恢复测试..." -ForegroundColor Gray
Start-Sleep -Seconds 3

try {
    $body = @{
        query = "你好"
        sessionId = "recovery-test"
    } | ConvertTo-Json
    
    $response = Invoke-RestMethod -Uri "$Url/api/agent/query" `
        -Method Post `
        -Body $body `
        -ContentType "application/json" `
        -TimeoutSec 5
    
    Write-Host "✅ 服务恢复正常" -ForegroundColor Green
}
catch {
    Write-Host "❌ 服务仍然无响应，可能需要重启" -ForegroundColor Red
}

Write-Host ""

# ========== 总结 ==========
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  测试完成" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "如果所有测试通过，说明服务配置正确✅" -ForegroundColor Green
Write-Host ""
Write-Host "建议：" -ForegroundColor Yellow
Write-Host "1. 使用 Mock 模式快速测试：Qwen.UseMock = true" -ForegroundColor White
Write-Host "2. 查看日志确认每90秒有健康检查" -ForegroundColor White
Write-Host "3. 长时间测试：让服务运行几小时后再访问" -ForegroundColor White
Write-Host ""

